package server.model.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import model.dto.UserDTO;
import model.enums.UserStatusType;

public class UsersDAO {

	private synchronized static ArrayList<UserDTO> getUsers(Connection dbConnection, String whereCondition){
		ArrayList<UserDTO> result=new ArrayList<UserDTO>();
		Statement stm=null;
		ResultSet rst=null;
		try{
			stm=dbConnection.createStatement();
			String query="SELECT * FROM users WHERE (1=1)";
			if(!whereCondition.equals("")){
				query+=" AND (" + whereCondition + ")";
			}
			rst=stm.executeQuery(query);
			while(rst.next()){
				result.add(new UserDTO(rst.getInt("id"), rst.getString("ip"), UserStatusType.valueOf(rst.getString("status"))));
			}
		} catch (SQLException e) {
			e.printStackTrace(System.err);
		}finally{
			try {
				rst.close();
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace(System.err);
			}
		}
		return result;
	}

	public static ArrayList<UserDTO> getAll(Connection dbConnection){
		return getUsers(dbConnection, "");
	}

	public static ArrayList<UserDTO> getOnlineUsers(Connection dbConnection){
		return getUsers(dbConnection, "status='online'");
	}

	public synchronized static boolean updateStatus(Connection dbConnection, Integer idUser, String status){
		if(status.equals("null")) return false;
		Statement stm=null;
		boolean response=false;
		try{
			stm=dbConnection.createStatement();
			response=(stm.executeUpdate("UPDATE users set status='" + status + "' WHERE id=" + idUser)>0);
		} catch (SQLException e) {
			e.printStackTrace(System.err);
		}finally{
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace(System.err);
			}
		}
		return response;
	}
}
